import { IHttpResponse, IParam } from '@/core/interface';
import { ControlVOBase } from '../control-vo';
import { CtrlServiceBase } from './ctrl-service-base';

/**
 * 向导面板服务
 *
 * @class WizardPanelService
 * @extends {CtrlServiceBase<T>}
 * @template T
 */
class WizardPanelService<T extends ControlVOBase> extends CtrlServiceBase<T> {
	/**
	 * 处理响应
	 *
	 * @param {IHttpResponse} response
	 * @param {*} [opts={}]
	 * @return {*}
	 * @memberof WizardPanelService
	 */
	handleResponse(response: IHttpResponse, opts: any = {}) {
		response.data = this.newControlVO(response.data);
		return response;
	}

	/**
	 * 初始化向导
	 *
	 * @param {string} action
	 * @param {IParam} [context={}]
	 * @param {IParam} [data={}]
	 * @return {*}  {Promise<IHttpResponse>}
	 * @memberof WizardPanelService
	 */
	async init(
		action: string,
		context: IParam = {},
		data: IParam = {}
	): Promise<IHttpResponse> {
		let result: Promise<any> | null = null;
		const { data: Data, context: Context } = this.handleRequestData(
			context,
			data
		);
		try {
			await this.initEntityService();
			if (this.appEntityService) {
				result = this.appEntityService[action ? action : 'Create'](
					Context,
					Data
				);
				if (result) {
					const response = await result;
					this.handleResponse(response);
				}
			}
		} catch (error) {}
		return result;
	}

	/**
	 * 完成向导
	 *
	 * @param {string} action
	 * @param {IParam} [context={}]
	 * @param {IParam} [data={}]
	 * @return {*}  {Promise<IHttpResponse>}
	 * @memberof WizardPanelService
	 */
	async finish(
		action: string,
		context: IParam = {},
		data: IParam = {}
	): Promise<IHttpResponse> {
		let result: Promise<any> | null = null;
		const { data: Data, context: Context } = this.handleRequestData(
			context,
			data
		);
		try {
			await this.initEntityService();
			Object.assign(Data, { ignoreversioncheck: 1 });
			if (this.appEntityService) {
				result = this.appEntityService[action ? action : 'Update'](
					Context,
					Data
				);
				if (result) {
					const response = await result;
					this.handleResponse(response);
				}
			}
		} catch (error) {}
		return result;
	}
}

export default WizardPanelService;
